package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.Permission;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DtsPermissionServiceImpl implements DtsPermissionService {
    @Autowired
    DtsPermissionMapper dtsPermissionMapper;
    @Override
    public Set<String> findPermissionByIds(Integer[] roleIds) {
        LambdaQueryWrapper<DtsPermission> qw = new LambdaQueryWrapper<>();
        qw.in(DtsPermission::getRoleId,roleIds);
        List<DtsPermission> dtsPermissions = dtsPermissionMapper.selectList(qw);
        Set<String> permission = dtsPermissions.stream().map(Permission -> {
            return Permission.getPermission();
        }).collect(Collectors.toSet());

        return permission;
    }

    @Override
    public void updatePermission(Integer roleId, ArrayList<String> permissions) {
        //删除该角色原有的权限
        LambdaQueryWrapper<DtsPermission> qw = new LambdaQueryWrapper<>();
        qw.eq(DtsPermission::getRoleId,roleId);
        dtsPermissionMapper.delete(qw);
        //给新角色添加权限
        if(permissions!=null&&permissions.size()>0){
            for (String permission : permissions) {
                DtsPermission dtsPermission = new DtsPermission();
                dtsPermission.setDeleted(false);
                dtsPermission.setAddTime(new Date());
                dtsPermission.setRoleId(roleId);
                dtsPermission.setUpdateTime(new Date());
                dtsPermission.setPermission(permission);
                dtsPermissionMapper.insert(dtsPermission);
            }
        }

    }
}
